//
//  MLAHttpManage.m
//  MagicLampApp
//
//  Created by Zheng on 2018/12/25.
//  Copyright © 2018 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAHttpManage.h"
#import "MLALoginVC.h"
#import "MLABaseNavController.h"

static MLAHttpManage *instance = nil;
AFHTTPSessionManager *manager;

@implementation MLAHttpManage

+ (NSURLSessionDataTask *)postHostType:(MLAHttpHostType)type
                                   api:(NSString *)api
                                params:(NSDictionary *)params
                               success:(void (^)(id _Nonnull,NSString *_Nonnull))success
                               failure:(void (^)(void))failure {
    [MLAHudManage showLoading];
    NSString *host = [[self class] getHostWithType:type];
    api = [NSString stringWithFormat:@"%@%@",host,api];
    NSString *token = [CX_GetUserDefaults() objectForKey:kAccessToken];
    token = token? token: @"";
    NSMutableDictionary *paramsDic = [[NSMutableDictionary alloc] initWithDictionary:params];
    [paramsDic setObject:token forKey:kAccessToken];
    
    NSURLSessionDataTask *task = [manager POST:api parameters:paramsDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MLAHudManage hideLoading];
        if ([responseObject[@"status"] integerValue] == 113701 || [responseObject[@"error_code"] integerValue] == 113701) {
            failure();
            NSLog(@"%@",responseObject);
            [CX_GetUserDefaults() removeObjectForKey:kAccessToken];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                MLALoginVC *loginVC = [[MLALoginVC alloc] init];
                MLABaseNavController *rootVC = [[MLABaseNavController alloc] initWithRootViewController:loginVC];
                CX_GetKeyWindow().rootViewController = rootVC;
            });
        } else if ([responseObject[@"status"] integerValue] == 200) {
            success(responseObject[@"response_data"],responseObject[@"message"]);
            if (responseObject[@"message"]) {
                if (![responseObject[@"message"] isEqualToString:@"SUCCESS"]) {
                    [MLAHudManage showMessage:responseObject[@"message"]];
                }
            } else {
                if (responseObject[@"error_msg"]) {
                    [MLAHudManage showMessage:responseObject[@"error_msg"]];
                }
            }
        } else if (responseObject[@"error_code"]) {
            failure();
            if (responseObject[@"message"]) {
                [MLAHudManage showMessage:responseObject[@"message"]];
            } else {
                if (responseObject[@"error_msg"]) {
                    [MLAHudManage showMessage:responseObject[@"error_msg"]];
                }
            }
        } else {
            success(@"",@"");
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MLAHudManage hideLoading];
        failure();
        CX_Log(@"%@",error);
        [MLAHudManage showMessage:@"网络可能出问题了..."];
    }];
    
    return task;
}


+ (NSURLSessionUploadTask *)uploadHostType:(MLAHttpHostType)type api:(NSString *)api params:(NSDictionary *)params success:(void (^)(id _Nonnull, NSString * _Nonnull))success failure:(void (^)(void))failure {
    [MLAHudManage showLoading];
    NSString *host = [[self class] getHostWithType:type];
    api = [NSString stringWithFormat:@"%@%@",host,api];
    NSString *token = [CX_GetUserDefaults() objectForKey:kAccessToken];
    token = token? token: @"";
    NSMutableDictionary *paramsDic = [[NSMutableDictionary alloc] initWithDictionary:params];
    NSData *imageData = paramsDic[@"file"];
    [paramsDic removeObjectForKey:@"file"];
    [paramsDic setObject:token forKey:kAccessToken];
    
    [manager POST:api parameters:paramsDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MLAHudManage hideLoading];
        if ([responseObject[@"status"] integerValue] == 200) {
            success(responseObject[@"response_data"],responseObject[@"message"]);
        } else {
            [MLAHudManage showMessage:@"上传失败,请重新上传"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MLAHudManage hideLoading];
        failure();
    }];

    return nil;
}

#pragma mark - 获取Host地址
+ (NSString *)getHostWithType:(MLAHttpHostType)type {
    NSString *host = @".deitylamp.com/";
    switch (type) {
        case MLAHttpHostType_Api:
            host = [NSString stringWithFormat:@"https://api%@admin.php?",host];
            break;
        case MLAHttpHostType_Diancan:
            host = [NSString stringWithFormat:@"https://diancan%@diancan/2.0/",host];
            break;
        case MLAHttpHostType_Jinxiaocun:
            host = [NSString stringWithFormat:@"https://jinxiaocun%@jinxiaocun/2.0/",host];
            break;
        case MLAHttpHostType_Wuye:
            host = [NSString stringWithFormat:@"https://wuye%@wuye/2.0/",host];
            break;
    }

    return host;
}


#pragma mark - 初始化
+ (void)load {
    [MLAHttpManage defaultManager];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        manager = [AFHTTPSessionManager manager];
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
        
    }
    return self;
}

+ (instancetype)defaultManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (instance) {
        return instance;
    } else {
        return [MLAHttpManage defaultManager];
    }
}

- (id)copy {
    return [MLAHttpManage defaultManager];
}

- (id)mutableCopy {
    return [MLAHttpManage defaultManager];
}




@end
